<?php

namespace App\Http\Controllers;

use App\Models\Products;
use App\Models\Sliderimg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function homePage(){

        //获取轮播图信息，并且传递给homepage页面
        $sliderInfo = $this->sliderimg();

        //获取所有商品
        $productsInfo = $this->allProducts();

        return view('homepage',['sliderInfo'=>$sliderInfo,'productsInfo'=>$productsInfo]);
    }

    public function sliderimg(){
        //第一张轮播图
        $imgone = Sliderimg::where('img_no','=',1)->first();
        $proid_one  = $imgone['products_id'];//对应的产品的id
        $imgfile_one = $imgone['sliderimgfile'];//轮播图的地址

        $proinfo_one  = Products::where('id','=',$proid_one)->first();
        $proname_one = $proinfo_one['name'];//商品的名称
        $proprice_one = $proinfo_one['price'];//商品的价格

        //第二张轮播图
        $imgtwo = Sliderimg::where('img_no','=',2)->first();
        $proid_two  = $imgtwo['products_id'];//对应的产品的id
        $imgfile_two = $imgtwo['sliderimgfile'];//轮播图的地址

        $proinfo_two  = Products::where('id','=',$proid_two)->first();
        $proname_two = $proinfo_two['name'];//商品的名称
        $proprice_two = $proinfo_two['price'];//商品的价格

        //第三张轮播图
        $imgthree = Sliderimg::where('img_no','=',3)->first();
        $proid_three  = $imgthree['products_id'];//对应的产品的id
        $imgfile_three = $imgthree['sliderimgfile'];//轮播图的地址

        $proinfo_three  = Products::where('id','=',$proid_three)->first();
        $proname_three = $proinfo_three['name'];//商品的名称
        $proprice_three = $proinfo_three['price'];//商品的价格

        $sliderInfo = array(
            array($proname_one,$proprice_one,$imgfile_one),
            array($proname_two,$proprice_two,$imgfile_two),
            array($proname_three,$proprice_three,$imgfile_three),
        );

        return $sliderInfo;
    }

    //获取所有商品
    public function allProducts(){
        //获取商品的预览图地址、分类、商品名称、概述、价格这5个数据
        $productsInfo = DB::table('products AS p')
            ->leftJoin('procategory AS c','p.procategory_id','=','c.category_no')
            ->select('p.*','c.name as catename')
            ->get();
        return $productsInfo;
    }
}
